﻿using IMES.Common.Domain.KeepModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Keep.API.Appliction.Command.workSheetFile
{
	/// <summary>
	/// 工单类型修改
	/// </summary>
	public class workSheetTypeHandler : IRequestHandler<workSheetTypeCommon, Result>
	{
		private readonly IBaseRepositorys<workSheet> _workSheetRep;
	    /// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="workSheetRep"></param>
		public workSheetTypeHandler(IBaseRepositorys<workSheet> workSheetRep)
		{
			_workSheetRep = workSheetRep;
		}
		public async Task<Result> Handle(workSheetTypeCommon request, CancellationToken cancellationToken)
		{
			var result = new Result() { Code = (int)CodeEnum.success, Messege = "工单类型修改成功" };
			try
			{
				//批量查询
				var workSheet = _workSheetRep.GetAll().Where(a => request.WorkSheetIds.Contains(a.WorkSheetId)).ToList();
				if (workSheet == null )
				{
                    result.Code = (int)CodeEnum.error;
                    result.Messege = "工单不存在";
					return result;
				}
				foreach (var item in workSheet)
				{
					item.State = (WorkSheetState)request.Types;//工单状态修改
					//开始时间更新
					if(request.Types == 2)
					{
						item.StartTime = DateTime.Now;
					}
					//结束时间更新
					if (request.Types == 3)
					{
						item.EndTime = DateTime.Now;
					} 
				}
				var n =  _workSheetRep.UpdateRange(workSheet);//批量更新
				if (n == 0)
				{
                    result.Code = (int)CodeEnum.error;
					result.Messege = "工单类型修改失败";
					return result;
				}
			}
			catch (Exception ex)
			{
				result.Code = (int)CodeEnum.error;
				result.Messege = ex.Message;
			} 
			 return result;
		}


	}
}
